import App from '@/common/js/app.js'
import _ from 'lodash'

const api_addbillorder = function(openid, cardid, billid, money) {
	return new Promise((resolve, reject) => {
		App._post_form2("entry/wxapp/apipayment.addbillorder", {
			"openid": openid,
			"form": {
				"cardid": cardid,
				"billid": billid,
				"money": money,
				"paytype": "14"
			}
		}, (res) => {
			resolve(res)
		})
	})
}

const api_icbcpay = function(openid, ordersn, money) {
	return new Promise((resolve, reject) => {
		App._post_form2("entry/wxapp/apipayment.icbcpay", {
			"openid": openid,
			"ordersn": ordersn,
			"money": money
			// "money": 0.01
		}, (res) => {
			resolve(res)
		})
	})
}

const pay = function(orderInfo) {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: 'payment',
			success(res) {
				console.log(res)
				if (res.provider.indexOf('wxpay') > -1) {
					console.log('开始支付')
					uni.requestPayment({
						"provider": "wxpay", //固定值为"wxpay"
						"timeStamp": orderInfo.timestamp,
						"nonceStr": orderInfo.noncestr,
						"package": orderInfo.package,
						"signType": orderInfo.signtype,
						"paySign": orderInfo.sign,
						success: (res) => {
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					});
				}
			}
		})
	})
}

const api_paysucc = function(openid, id, order_id) {
	return new Promise((resolve, reject) => {
		App._post_form2(
			"entry/wxapp/apipayment.paysucc", {
				"openid": openid,
				"id": id,
				"pay_order_no": order_id
			}, (res) => {
				resolve(res)
			})
	})
}

const api_paybill = function(id, openid, orderid, formData) {
	return new Promise((resolve, reject) => {
		App._post_form2(
			"entry/wxapp/apipayment.paybill", {
				"id": id,
				"openid": openid,
				"orderid": orderid,
				"form": formData
			}, (res) => {
				resolve(res)
			})
	})
}

/**
 * 设置支付流程
 * @param {Object} billid
 * @param {Object} flowFlag
 * @param {Object} money
 * @param {Object} id
 */
const setPayFlow = function (itemData, billid, flowFlag, money, id) {
	let payFlows = uni.getStorageSync('payFlows')
	if (payFlows) {
		let flowItem = _.find(payFlows, {id: id})
		if (flowItem) {
			flowItem.flowFlag = flowFlag
		} else {
			payFlows.unshift({
				itemData: itemData,
				billid: billid,
				flowFlag: flowFlag,
				money: money,
				id: id
			})
		}
		uni.setStorageSync('payFlows', payFlows)
	}else {
		let newPayFlows = []
		newPayFlows.unshift({
			itemData: itemData,
			billid: billid,
			flowFlag: flowFlag,
			money: money,
			id: id
		})
		uni.setStorageSync('payFlows', newPayFlows)
	}
}

export default {
	api_addbillorder,
	api_icbcpay,
	pay,
	api_paysucc,
	api_paybill,
	setPayFlow
}